package com.cgah

import grails.converters.JSON


class ExpiredListingDetectorJob {
    def timeout = 5000l // execute job once in 5 seconds
    def listingService
    def emailService
    def jmsTemplate

    def execute() {
        // Check for expired listings. If found, throw them on the queue.
        def expiredListings = listingService.getExpiredListings()
        putListingsOnMessageQueue(expiredListings)
        emailService.sendListingExpiredNotifications(expiredListings)
    }

    def putListingsOnMessageQueue(def listings)
    {
        // Add the Listings to the queue
        for (listing in listings)
        {
            try
            {
                // Sending the listing as JSON provides the information required by C2
                jmsTemplate.convertAndSend("listingQueue", (listing as JSON).toString())
            }
            catch(e)
            {
                log.error "Error placing listing (id: ${listing?.id}) on the JMS queue: ${e.message}"
            }
        }
    }
}
